<template>
  <view class="container" :style="{ backgroundImage: `url(${counterStore.bg_img})` }">
    <!-- 顶部占位，用于适配安全区域 -->
    <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <view class="back-button" @tap="goBack">
        <text class="back-icon">←</text>
      </view>
    </view>
    <!-- 顶部提示文字，告知用户操作 -->
    <view class="tip-text">请点击下方的卡片选择您的牌（正位/逆位）</view>
    <!-- 卡片区域，循环渲染卡片 -->
    <view class="cards-container">
      <view 
        v-for="(index, cardIndex) in cardCount" 
        :key="index" 
        class="card-item"
        :class="{ selected: selectedCards.includes(cardIndex) }"
        @tap="selectCard(cardIndex)"
      >
        <view class="card-content">
          <!-- 卡片区域的图片 -->
          <image 
            v-if="displayedCardImages[cardIndex]"
            :src="displayedCardImages[cardIndex]"
            class="card-image"
            :class="{ 'card-reverse': selectedCardsPosition[cardIndex] === 'down' }"
            mode="aspectFit"
            lazy-load
            @load="handleImageLoad"
            @error="handleImageError"
          />
          <image 
            v-else
            class="card-image"
            :class="{ 'card-reverse': selectedCardsPosition[cardIndex] === 'down' }"
            mode="aspectFit"
            :src="getCardImage(cardIndex)"
            lazy-load
          />
          <text v-if="displayedCardTitles[cardIndex]" class="selected-card-title">
            {{displayedCardTitles[cardIndex]}}
          </text>
        </view>
      </view>
    </view>
    <!-- 底部按钮，触发解牌操作 -->
    <view class="bottom-button" @tap="startReading">
      AI解牌
    </view>
    <!-- 添加自助抽牌按钮 -->
    <view class="auto-draw-button" @tap="handleAutoDraw">
      自助抽牌
    </view>
    <!-- 卡片详情弹窗，点击卡片时显示，用于选择卡牌方向和图片 -->
    <view class="popup" v-if="showPopup" @tap.stop="closePopup">
      <view class="popup-content" @tap.stop>
        <view class="popup-header">
          <text class="popup-title">选择卡牌方向</text>
          <!-- 正位按钮，点击切换卡牌方向为正位 -->
          <view 
            class="position-btn"
            :class="{ active: tempPosition === 'up' }"
            @tap="selectPosition('up')"
          >
            正位
          </view>
          <!-- 逆位按钮，点击切换卡牌方向为逆位 -->
          <view 
            class="position-btn"
            :class="{ active: tempPosition === 'down' }"
            @tap="selectPosition('down')"
          >
            逆位
          </view>
          <!-- 关闭按钮，点击关闭弹窗 -->
          <text class="popup-close" @tap="closePopup">×</text>
        </view>
        <view class="popup-body">
          <!-- 循环渲染图片列表，显示标题和图片 -->
          <view 
            v-for="(item, index) in imgsCard" 
            :key="index" 
            class="pop-img"
          >
            <view class="card-item-container">
              <image 
                :src="item.src" 
                @tap="selectImage(index, item.src)"
                mode="aspectFit"
                lazy-load
                @load="handleImageLoad"
                @error="handleImageError"
              />
              <text class="card-title">{{item.title}}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import cardData from '@/db/index.json'  // 导入卡牌数据
import {useCounterStore} from '@/store/counter'

const counterStore = useCounterStore()

// 获取屏幕边界到安全区域距离（未在去除逻辑中使用，若后续无相关功能可考虑删除）
const { safeAreaInsets } = uni.getSystemInfoSync() 

// 获取页面参数，用于确定卡片数量
const cardCount = ref(0)
// 存储已选中的卡片索引
const selectedCards = ref<number[]>([])
// 存储已选中卡片的正逆位状态
const selectedCardsPosition = ref<Record<number, 'up' | 'down'>>({})
// 默认的卡片方向
const cardPosition = ref<'up' | 'down'>('up')

// 控制弹窗显示与隐藏
const showPopup = ref(false)
// 当前点击的卡片索引
const currentCard = ref<number>(0)
// 当前选择的卡牌方向
const tempPosition = ref<'up' | 'down'>('up')
// 存储点击的图片的src
const clickedImageSrc = ref<string | null>(null)
// 存储每个卡片位置显示的图片src
const displayedCardImages = ref<Record<number, string | null>>({})
// 存储每个卡片位置显示的标题
const displayedCardTitles = ref<Record<number, string | null>>({})
// 所有可供选择的图片列表
const imgsCard = ref(cardData.cards)//卡牌数据


// 使用组合式 API 的生命周期钩子，获取页面传递的参数
onLoad((option: any) => {
  if (option && option.count) {
    cardCount.value = parseInt(option.count)
  }
})

// 选择卡片方法
const selectCard = (index: number) => {
  currentCard.value = index;
  
  // 如果卡片已经选中，设置临时方向为当前卡片的方向
  if (selectedCards.value.includes(index)) {
    tempPosition.value = selectedCardsPosition.value[index] || 'up';
  } else {
    // 如果是新卡片，使用默认方向
    tempPosition.value = cardPosition.value;
  }
  
  showPopup.value = true;
}

// 关闭弹窗方法
const closePopup = () => {
  showPopup.value = false;
}

// 选择卡片方向方法
const selectPosition = (position: 'up' | 'down') => {
  tempPosition.value = position;
  // 更新当前卡片的方向
  const currentIndex = currentCard.value;
  if (currentIndex >= 0) {
    selectedCardsPosition.value[currentIndex] = position;
    // 如果已经选择了图片，立即更新显示
    if (displayedCardImages.value[currentIndex]) {
      const currentImage = displayedCardImages.value[currentIndex];
      displayedCardImages.value[currentIndex] = currentImage;
    }
  }
}

// 选择图片方法
const selectImage = (cardIndex: number, src: string) => {
  // 检查图片是否已经被选中
  const isImageSelected = Object.values(displayedCardImages.value).includes(src);
  if (isImageSelected) {
    uni.showToast({
      title: '该图片已被选中，请选择其他图片',
      icon: 'none'
    });
    return;
  }

  // 如果是当前选中的卡片，直接更新图片和标题
  if (selectedCards.value.includes(currentCard.value)) {
    displayedCardImages.value[currentCard.value] = src;
    // 根据src找到对应的卡片标题
    const selectedCard = imgsCard.value.find(card => card.src === src);
    if (selectedCard) {
      displayedCardTitles.value[currentCard.value] = selectedCard.title;
    }
    closePopup();
    return;
  }

  // 如果还没选满卡片数量，找到第一个空位
  if (selectedCards.value.length < cardCount.value) {
    let firstEmptyIndex = 0;
    while (selectedCards.value.includes(firstEmptyIndex) && firstEmptyIndex < cardCount.value) {
      firstEmptyIndex++;
    }
    
    if (firstEmptyIndex < cardCount.value) {
      selectedCards.value.push(firstEmptyIndex);
      selectedCardsPosition.value[firstEmptyIndex] = tempPosition.value;
      displayedCardImages.value[firstEmptyIndex] = src;
      // 设置对应的标题
      const selectedCard = imgsCard.value.find(card => card.src === src);
      if (selectedCard) {
        displayedCardTitles.value[firstEmptyIndex] = selectedCard.title;
      }
    }
  } else {
    uni.showToast({
      title: `最多只能选择${cardCount.value}张牌`,
      icon: 'none'
    });
  }
  closePopup();
}

// 开始解牌方法
const startReading = () => {
  if (selectedCards.value.length === cardCount.value) {
    // 准备要传递的卡牌数据
    const cardsData = selectedCards.value.map(index => ({
      image: displayedCardImages.value[index],
      name: displayedCardTitles.value[index],
      position: selectedCardsPosition.value[index] || 'up'
    }))

    // 跳转到支付页面并传递数据
    uni.navigateTo({
      url: '../payment/payment?cards=' + encodeURIComponent(JSON.stringify(cardsData)),
      fail: (err) => {
        console.error('跳转失败:', err)
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  } else {
    uni.showToast({
      title: `请选择${cardCount.value}张牌`,
      icon: 'none'
    })
  }
}

// 获取卡片图片方法
const getCardImage = (index: number) => {
  if (selectedCards.value.includes(index)) {
    return displayedCardImages.value[index] || '/static/images/tarot_card.png';
  } else {
    return '/static/images/tarot_card.png';
  }
}

// 自助抽牌相关
const autoDrawCardImage = ref('')
const autoDrawCardTitle = ref('')
const autoDrawIsReverse = ref(false)
const autoDrawCardIndex = ref(-1)

// 处理自助抽牌
const handleAutoDraw = () => {
  // 如果还没选满卡片数量
  if (selectedCards.value.length < cardCount.value) {
    // 随机选择一张卡片（0-77）
    const randomIndex = Math.floor(Math.random() * imgsCard.value.length)
    const selectedCard = imgsCard.value[randomIndex]
    // 随机决定正逆位
    const isReverse = Math.random() > 0.5
    
    // 找到第一个空位
    let firstEmptyIndex = 0
    while (selectedCards.value.includes(firstEmptyIndex) && firstEmptyIndex < cardCount.value) {
      firstEmptyIndex++
    }
    
    if (firstEmptyIndex < cardCount.value) {
      // 直接添加卡片
      selectedCards.value.push(firstEmptyIndex)
      selectedCardsPosition.value[firstEmptyIndex] = isReverse ? 'down' : 'up'
      displayedCardImages.value[firstEmptyIndex] = selectedCard.src
      displayedCardTitles.value[firstEmptyIndex] = selectedCard.title
      
      // 显示抽牌结果提示
      uni.showToast({
        title: `抽到：${selectedCard.title} (${isReverse ? '逆位' : '正位'})`,
        icon: 'none',
        duration: 2000
      })
    }
  } else {
    uni.showToast({
      title: `最多只能选择${cardCount.value}张牌`,
      icon: 'none'
    })
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack({
    fail: (err) => {
      console.error('返回失败:', err)
      uni.showToast({
        title: '返回失败',
        icon: 'none'
      })
    }
  })
}
// 图片加载处理方法
const handleImageLoad = (e) => {
  console.log('图片加载成功')
}

const handleImageError = (e) => {
  console.error('图片加载失败:', e)
  uni.showToast({
    title: '图片加载失败',
    icon: 'none'
  })
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: linear-gradient(180deg, #1a1a2e 0%, #16213e 100%);
  padding: 4vw 2vw; 
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.tip-text {
  color: #fff;
  font-size: 3.2vw;
  text-align: center;
  margin-bottom: 3vw;
}

.position-selector {
  display: flex;
  justify-content: center;
  gap: 4vw;
  margin-bottom: 3vw;
}

.position-option {
  display: flex;
  align-items: center;
  gap: 1vw;
  color: rgba(255, 255, 255, 0.6);
  font-size: 2.8vw;
  padding: 1vw 2vw;
  border-radius: 3vw;
  transition: all 0.3s;
}

.position-option.active {
  color: #fff;
  background: rgba(39, 186, 155, 0.2);
}

.cards-container {
  margin-top: 10vh;
  flex: 1;
  display: flex;
  justify-content: center;
  gap: 3vw;
  flex-wrap: wrap;
}

.card-item {
  width: 23vw;
  height: 25vh;
  background: rgba(255, 255, 255, 0.1);
  border: 0.2vw solid rgba(255, 255, 255, 0.2);
  border-radius: 1.6vw;
}

.card-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.card-image {
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.05);
  transition: transform 0.3s ease;
  /* 添加占位背景 */
  background-color: #f5f5f5;
  /* 添加渐变动画 */
  transition: opacity 0.3s ease-in-out;
}

.card-reverse {
  transform: rotate(180deg);
}

.card-item.selected {
  border-color: #27ba9b;
  box-shadow: 0 0 2vw rgba(39, 186, 155, 0.3);
}

.bottom-button {
  height: 9vh;
  background: linear-gradient(90deg, #27ba9b 0%, #1f9d82 100%);
  border-radius: 4.5vw;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 3.2vw;
  font-weight: bold;
  margin: 0 4vw;
}

.bottom-button:active {
  opacity: 0.8;
}

.popup {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.popup-content {
  background: #fff;
  border-radius: 4vw 4vw 0 0;
  width: 100%;
  max-height: 85vh;
  position: relative;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.popup-header {
  padding: 3vw;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.popup-body {
  padding: 3vw;
  max-height: 70vh;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 2vw;
}

.card-item-container {
  width: 100%;
  aspect-ratio: 1/1.5;
  position: relative;
}

.card-item-container image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 1vw;
}

.card-title {
  margin-top: 1vw;
  font-size: 2.8vw;
  color: #333;
  text-align: center;
}

.position-buttons {
  display: flex;
  justify-content: center;
  height: 10vh;
  gap: 3vw;
}

.position-btn {
  height: 2.5vh;
  padding: 1.5vw 4vw;
  border-radius: 3vw;
  color: #666;
  background: #f5f5f5;
  transition: all 0.3s;
}

.position-btn.active {
  color: #fff;
  background: #27ba9b;
}

.confirm-btn {
  background: #27ba9b;
  border-radius: 4vw;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 10vw;
  font-weight: bold;
}

.confirm-btn:active {
  opacity: 0.8;
}

.selected-card-title {
  margin-top: 1vw;
  font-size: 2.8vw;
  color: #fff;
  text-align: center;
  padding: 1vw;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 1vw;
  width: 80%;
}

/* 自助抽牌按钮样式 */
.auto-draw-button {
  height: 9vh;
  background: linear-gradient(90deg, #ff6b6b 0%, #ee5253 100%);
  border-radius: 4.5vw;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 3.2vw;
  font-weight: bold;
  margin: 2vh 4vw;
}

.auto-draw-button:active {
  opacity: 0.8;
}

/* 自助抽牌弹窗样式 */
.auto-draw-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.auto-draw-content {
  width: 80vw;
  background: #fff;
  border-radius: 2vw;
  padding: 3vw;
}

.auto-draw-card {
  width: 100%;
  height: 50vh;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 3vw 0;
}

.auto-draw-image {
  width: 60%;
  height: 100%;
  transition: transform 0.3s;
}

.card-info {
  text-align: center;
  margin-bottom: 3vw;
}

.card-info .card-title {
  font-size: 3.6vw;
  color: #333;
  font-weight: bold;
  margin-bottom: 1vw;
  display: block;
}

.card-info .card-position {
  display: inline-block;
  padding: 1vw 3vw;
  background: rgba(39, 186, 155, 0.1);
  color: #27ba9b;
  border-radius: 3vw;
  font-size: 2.8vw;
}

.action-buttons {
  display: flex;
  gap: 2vw;
}

.action-btn {
  flex: 1;
  height: 9vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 1vw;
  font-size: 2.8vw;
  color: #666;
}

.action-btn.primary {
  background: #27ba9b;
  color: #fff;
}

.action-btn:active {
  opacity: 0.8;
}

.navbar {
  position: relative;
  height: 12vw;
  display: flex;
  align-items: center;
  margin-bottom: 4vw;
}

.back-button {
  position: relative;
  width: 8vw;
  height: 8vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  border-radius: 50%;
}

.back-icon {
  color: #fff;
  font-size: 5vw;
}
</style>